package com.qf.controller;

import com.qf.util.UploadUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/*
杨威
2021/9/17
15:23
*/
@WebServlet("/downLoad")
public class DownLoadController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //1收参
        String fileName = request.getParameter("fileName");
        //截取出源文件名称
        String s = fileName.substring(fileName.indexOf("_") + 1);
        //根据原文件名称获取文件所在文件夹路径
        String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
        String newFilePath = UploadUtil.creatNewFilePath(realPath, s);
        //文件路径
        String downPath=newFilePath+ File.separator+fileName;

        response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(s,"utf-8"));
        FileInputStream fis=new FileInputStream(downPath);
        ServletOutputStream outputStream = response.getOutputStream();

        int i =-1;
        while((i=fis.read())!=-1){
            outputStream.write(i);
        }
        fis.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
